package com.baibei.ebec.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.baibei.module.AppRouter;
import com.baibei.sdk.Empty;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by tang on 2018/4/19.
 */

public class JpushReceiver extends BroadcastReceiver {

    public JpushReceiver(){

    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        Log.i("jpushhh","[MyReceiver] onReceive - " + intent.getAction()
                + ", extras: " + printBundle(bundle));
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.i("jpushhh", "regId=" + regId);
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())){
            Log.i("jpush", "[MyReceiver] 接收到推送下来的自定义消息: "
                            + bundle.getString(JPushInterface.EXTRA_MESSAGE));
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())){
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())){
            Log.e("jpushhh","打开了推送消息："+bundle.getString(JPushInterface.EXTRA_ALERT));
            Log.e("jpushhhh", "推送消息的key是："+bundle.get(JPushInterface.EXTRA_EXTRA ));

            String extra = bundle.getString(JPushInterface.EXTRA_EXTRA);
            Gson gson = new Gson();
            HashMap<String, String> map = new HashMap<>();
            map = gson.fromJson(extra, map.getClass());
            String extrakey = map.get("extrakey");
            Log.e("jpushhh",map+"+"+extrakey);

            toMessage(context,extrakey);
        }else {
            Log.i("jpushhh", "[MyReceiver] Unhandled intent - " + intent.getAction());
        }
    }

    private void toMessage(Context context,String extrakey) {

        AppRouter.routeToMessage(context,extrakey);
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }
}
